package com.ruoyi.chat.service;

import com.ruoyi.chat.domain.GameFileEntity;
import com.ruoyi.chat.mapper.GameFileMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

@Service
public class GameFileScanner {

    // 路径配置
    private static final String BASE_LOCAL_PATH = "/mnt/14T/games";
    private static final String ALIST_DOMAIN = "http://dav.yutang1314.fun:9000";
    private static final String LOCAL_DOMAIN = "http://192.168.1.66:5244";

    @Resource
    GameFileMapper gameMapper;

    public  Integer getGameFile() throws IOException{
        List<GameFileEntity> fileList = scanGameFiles();
        System.out.println("已扫描 " + fileList.size() + " 个文件");
        // 保存到数据库
        return saveToDatabase(fileList);
    }

    /**
     * 扫描游戏文件
     */
    private static List<GameFileEntity> scanGameFiles() throws IOException {
        List<GameFileEntity> fileList = new ArrayList<>();
        Path basePath = Paths.get(BASE_LOCAL_PATH);

        Files.walk(basePath, FileVisitOption.FOLLOW_LINKS)
                .filter(Files::isRegularFile)
                .forEach(filePath -> {
                    try {
                        File file = filePath.toFile();
                        String fileName = file.getName();
                        
                        // 计算相对路径
                        String relativePath = basePath.relativize(filePath).toString();
                        
                        // 获取文件扩展名和类型
                        String fileExtension = getFileExtension(fileName);
                        String fileType = getFileType(fileExtension);
                        
                        // 获取文件大小
                        long fileSizeBytes = file.length();
                        String fileSizeHuman = getHumanReadableSize(fileSizeBytes);


                        GameFileEntity gameFile = new GameFileEntity();
                        gameFile.setName(fileName);
                        gameFile.setExtension(fileExtension);
                        gameFile.setType(fileType);
                        gameFile.setRelativePath("/d/" + relativePath);
                        gameFile.setSize(fileSizeHuman);
                        gameFile.setLocalPrefix(LOCAL_DOMAIN);
                        gameFile.setDomainPrefix(ALIST_DOMAIN);
                        
                        fileList.add(gameFile);
                        
                    } catch (Exception e) {
                        System.err.println("处理文件出错: " + filePath + ", error: " + e.getMessage());
                    }
                });

        return fileList;
    }

    /**
     * 获取文件扩展名
     */
    private static String getFileExtension(String fileName) {
        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex).toLowerCase();
        }
        return "";
    }

    /**
     * 获取文件类型（去掉点号）
     */
    private static String getFileType(String fileExtension) {
        if (fileExtension != null && fileExtension.length() > 1) {
            return fileExtension.substring(1); // 去掉点号
        }
        return "unknown";
    }

    /**
     * 将字节数转换为易读的格式
     */
    private static String getHumanReadableSize(long sizeBytes) {
        if (sizeBytes == 0) {
            return "0B";
        }

        String[] sizeNames = {"B", "KB", "MB", "GB", "TB"};
        int i = 0;
        double size = (double) sizeBytes;

        while (size >= 1024 && i < sizeNames.length - 1) {
            size /= 1024;
            i++;
        }

        // 根据大小选择合适的精度
        int precision;
        if (i == 0) { // B
            precision = 0;
        } else if (size < 10) { // 小于10的数字显示2位小数
            precision = 2;
        } else if (size < 100) { // 小于100的数字显示1位小数
            precision = 1;
        } else { // 大于100的数字显示整数
            precision = 0;
        }

        DecimalFormat df = new DecimalFormat();
        df.setMaximumFractionDigits(precision);
        df.setMinimumFractionDigits(precision);
        
        return df.format(size) + sizeNames[i];
    }

    /**
     * 全删全插
     */
    private int saveToDatabase(List<GameFileEntity> fileList) {
        // 先删除所有数据
        gameMapper.delete(null);
        // 批量插入新数据
        fileList.forEach(gameMapper::insert);
        return fileList.size();
    }

}